package com.alan.learn.fluentValidator;

import com.alan.learn.common.CommonUtil;
import com.baidu.unbiz.fluentvalidator.ValidationError;
import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorContext;
import com.baidu.unbiz.fluentvalidator.ValidatorHandler;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by liufan
 * 2019-10-14
 */
public class PhoneValidator extends ValidatorHandler<String> implements Validator<String> {

    private String fieldName;

    public PhoneValidator(String fieldName) {
        this.fieldName = fieldName;
    }
    @Override
    public boolean validate(ValidatorContext context, String s) {

        if(StringUtils.isNotBlank(s) && !s.matches(CommonUtil.PHONEREG)){
            context.addError(ValidationError.create(String.format("%s格式不正确！", fieldName))
                    .setErrorCode(-1)
                    .setField(fieldName)
                    .setInvalidValue(s));
            return false;
        }
        return true;
    }

}
